﻿// #Region FileInfo
// Creater:  程邵磊
// FileName:  JsonTimeConverter.cs
// CreateTime:  2018/10/28
// #EndRegion
// 

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Groove.Core.Infrastructure
{
    /// <summary>
    /// Customer Json time converter
    /// </summary>
    public class JsonTimeConverter : IsoDateTimeConverter
    {
        /// <summary>
        /// .Ctor
        /// </summary>
        public JsonTimeConverter()
        {
            DateTimeFormat = DateTimeFormatStrings.LongTimeFormatString;
        }

        /// <summary>
        /// CanConvert
        /// </summary>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public override bool CanConvert(Type objectType)
        {
            if (objectType == typeof(DateTime) || objectType == typeof(DateTime?))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// ReadJson
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var date = base.ReadJson(reader, objectType, existingValue, serializer) as DateTime?;
            return date;
        }

        /// <summary>
        /// WriteJson
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var date = value as DateTime?;
            base.WriteJson(writer, date ?? value, serializer);
        }
    }
}